<?php
// this php file takes in the id of the entity to be voteup or voteddown and the id of the presently logged in
// user and then stores the information in the database
// returns the string "success" on success and some other shit otherwise
require_once("../../connection.php");

$baseid = $_POST['baseid'];
$action = $_POST['action'];
$user = $_POST['user'];

$result = mysql_query("SELECT * FROM site_votes WHERE `user`='$user' AND `target`='$baseid'");
if(!$result) { echo "something went wrong: ".mysql_error(); die(); } 

if(mysql_numrows($result)!=0)
{
	$vote = mysql_result($result, 0, 'vote');
	if($vote  == "1") 
	{
		if($action == "voteup")
		{ echo "again"; die();}
		if($action == "votedown")
		$temp = mysql_query("UPDATE site_votes SET `vote`='0' WHERE `user`='$user' AND `target`='$baseid'");
		if(!$temp) echo mysql_error(); 
		else echo "success";
	}
	else if($vote == "-1")
	{
		if($action == "votedown")
		{ echo "again"; die();} 
		if($action == "voteup")
		$temp = mysql_query("UPDATE site_votes SET `vote`='0' WHERE `user`='$user' AND `target`='$baseid'");
		if(!$temp) echo mysql_error(); 
		else echo "success";
	}
	else if($vote == 0)
	{
		if($action == "voteup")
		$temp = mysql_query("UPDATE site_votes SET `vote`='1' WHERE `user`='$user' AND `target`='$baseid'");
		else if($action == "votedown")
		$temp = mysql_query("UPDATE site_votes SET `vote`='-1' WHERE `user`='$user' AND `target`='$baseid'");
		if(!$temp) echo mysql_error();
			else echo "success";
	}
}
else
	{
		if($action == "voteup")
		$temp = mysql_query("INSERT INTO site_votes (`target`,`user`,`vote`) VALUES('$baseid','$user','1')");
		else if($action == "votedown")
		$temp = mysql_query("INSERT INTO site_votes (`target`,`user`,`vote`) VALUES('$baseid','$user','-1')");
		
		if(!$temp) echo mysql_error();
		else echo "success";
	}
?>